package com.example.codec;

import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.Unmarshaller;

import java.io.IOException;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/30 10:14
 */
public class MarshallingDecoder {

    Unmarshaller unmarshaller;

    public MarshallingDecoder() throws IOException {
        this.unmarshaller = MarshallingCodecFactory.buildUnmarshalling();
    }

    protected Object decode(ByteBuf in) throws Exception {
        // 读取对象长度
        final int objSize = in.readInt();
        // 读取对象内容
        final ByteBuf buf = in.slice(in.readerIndex(), objSize);

        final ByteInput input = new ByteInputAdapter(buf);

        try {
            this.unmarshaller.start(input);
            final Object object = this.unmarshaller.readObject();
            this.unmarshaller.finish();
            in.readerIndex(in.readerIndex() + objSize);
            return object;
        } finally {
            this.unmarshaller.close();
        }
    }

}